<template>
    <div class="the-list">
        <div class="panel-search">
            <el-form inline :model="tableData.query" class="demo-form-inline">

                <el-form-item label="订单号">
                    <el-input v-model="tableData.query.orderNo" placeholder="订单号" clearable/>
                </el-form-item>

                <el-form-item label="申请人">
                    <el-input v-model="tableData.query.applyName" placeholder="申请人" clearable/>
                </el-form-item>

                <el-form-item label="申请人手机号">
                    <el-input v-model="tableData.query.applyPhone" placeholder="手机号" clearable/>
                </el-form-item>

                <el-form-item label="申请时间">
                    <el-date-picker :model-value="tableData.special.createdAt"
                                    value-format="YYYY-MM-DD HH:mm:ss" type="datetimerange" range-separator="至"
                                    start-placeholder="开始时间" end-placeholder="结束时间"
                                    @update:modelValue="tableFn.detetimeChange($event)"/>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="tableFn.onSubmit">搜索</el-button>
                    <el-button type="primary" @click="tableFn.onResetQuery">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="panel-table">
            <el-tabs @tab-click="tableFn.handleClick">
                <el-tab-pane v-for="(item,index) in tableData.orderstatusList" :name="item.refundStatus" :label="item.tabName" :key="index">
                    <div class="table-head">
                        <div>
                            数据列表
                        </div>
                    </div>
                    <el-table :data="tableData.list" stripe :header-cell-style="{backgroundColor:'#ededed',padding:'12px 0'}" style="width: 100%;" border>
                        <el-table-column prop="orderNo" label="订单号" />
                        <el-table-column prop="applyName" label="申请人" />
                        <el-table-column prop="applyPhone" label="手机号" />
                        <el-table-column prop="applyRefundMoney" label="退款金额（元）" >
                          <template #default="{ row }">
                            {{
                              row.refundMoney ? row.refundMoney/100 : row.applyRefundMoney/100
                            }}
                          </template>
                        </el-table-column>
                        <el-table-column prop="createdAt" label="申请时间" />
                        <el-table-column prop="orderType" label="订单类型" >
                            <template #default="scope">
                                <text>{{refundDetailsFn.parseOrderType(scope.row.orderType)}}</text>
                            </template>
                        </el-table-column>
                        <el-table-column prop="refundReason" label="退款理由" />

                        <el-table-column fixed="right" label="操作" width="280px" align="center">
                            <template #default="{row}">
                                <el-button size="small" type="primary" plain @click="refundDetailsFn.openDialog(row)">退款详情</el-button>
                                <el-button size="small" type="primary" plain @click="tableFn.toOrderDetails(row)">订单详情</el-button>
                                <el-button v-if="(row.refundStatus == 0 || row.refundStatus == 1)  && hasPermission(['orderCare:refundManage:auth'])" size="small" type="primary" plain @click="auditFn.openDialog(row)">审核</el-button>
                                <el-button v-if="row.refundStatus == 5 && hasPermission(['orderCare:refundManage:again'])" size="small" type="primary" plain @click="()=>{}">重新打款</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>

            <div class="table-pagination">
                <pagination :total="tableData.total" v-model:page="tableData.query.page" v-model:limit="tableData.query.pageSize" @pagination="tableFn.getTableList" />
            </div>
        </div>

        <!--审核-->
        <el-dialog v-model="auditData.auditVisible" title="审核">
            <el-form :model="auditData.obj" ref="auditForm" :rules="auditData.auditRules">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="审核结果" label-width="80px" prop="refundMoney">
                            <el-radio-group v-model="auditData.obj.auditRes" class="ml-4">
                                <el-radio label="1" size="large">同意退款</el-radio>
                                <el-radio label="2" size="large">驳回</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row v-if="auditData.obj.auditRes == '1'">
                    <el-col :span="6">
                        <el-form-item label="退款金额" label-width="80px" prop="refundMoney">
                            <div style="display: flex">
                                <el-input v-if="auditData.obj.refundStatus == '0'" maxlength="20" v-model="auditData.obj.refundMoney" autocomplete="off" @input="auditFn.payMoneyChangeHandle"/>
                                <text v-if="auditData.obj.refundStatus != '0'">{{auditData.obj.refundMoney}}</text>
                                <text>元</text>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row v-if="auditData.obj.auditRes == '2'">
                    <el-col :span="24">
                        <el-form-item label="驳回理由" label-width="80px" prop="rejectReason">
                            <el-input maxlength="255" type="textarea" v-model="auditData.obj.rejectReason"/>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                              <span class="dialog-footer">
                                <el-button @click="auditFn.closeDialog">取消</el-button>
                                <el-button type="primary" @click="auditFn.auditSubmit(auditForm)">确认</el-button>
                              </span>
            </template>
        </el-dialog>

        <!--退款详情-->
        <el-dialog v-model="refundDetailsData.refundDetailsVisible" title="退款详情">
            <el-collapse v-model="refundDetailsData.activeNames">
                <el-form :model="refundDetailsData.obj" label-width="80px" label-position="right">
                    <el-collapse-item title="退款信息" name="0">
                      <el-row>
                        <el-col :span="7">
                            <el-form-item label="订单号" label-width="70px">
                                <text class="orderInfoClass">{{refundDetailsData.obj.orderNo}}</text>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="订单类型" label-width="70px">
                                <text class="orderInfoClass">{{refundDetailsFn.parseOrderType(refundDetailsData.obj.orderType)}}</text>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="申请时间" label-width="70px">
                                <text class="orderInfoClass">{{refundDetailsData.obj.createdAt}}</text>
                            </el-form-item>
                        </el-col>
                        </el-row>
                      <el-row>
                        <el-col :span="7">
                          <el-form-item label="申请人" label-width="70px">
                              <text class="orderInfoClass">{{refundDetailsData.obj.applyName}}</text>
                          </el-form-item>
                        </el-col>
                        <el-col :span="6">
                          <el-form-item label="手机号" label-width="70px">
                              <text class="orderInfoClass">{{refundDetailsData.obj.applyPhone}}</text>
                          </el-form-item>
                        </el-col>
                        <el-col :span="6">
                          <el-form-item label="退款金额" label-width="70px">
                            <text class="orderInfoClass">
                              {{refundDetailsData.obj.refundMoney ? refundDetailsData.obj.refundMoney/100 : refundDetailsData.obj.applyRefundMoney/100}}</text>
                          </el-form-item>
                        </el-col>
                        </el-row>
                      <el-row>
                        <el-col :span="7">
                          <el-form-item label="订单金额" label-width="70px">
                            <text class="orderInfoClass">
                              {{refundDetailsData.obj.orderMoney ? refundDetailsData.obj.orderMoney/100 : refundDetailsData.obj.orderMoney/100}}
                            </text>
                          </el-form-item>
                        </el-col>
                        <el-col :span="6">
                          <el-form-item label="实付金额" label-width="70px">
                            <text class="orderInfoClass">
                              {{refundDetailsData.obj.payMoney ? refundDetailsData.obj.payMoney/100 : refundDetailsData.obj.payMoney/100}}
                            </text>
                          </el-form-item>
                        </el-col>
                        <el-col :span="6">
                          <el-form-item label="使用优惠券金额" label-width="110px">
                            <text class="orderInfoClass">
                              {{refundDetailsData.obj.couponMoney ? refundDetailsData.obj.couponMoney/100 : refundDetailsData.obj.couponMoney/100}}</text>
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </el-collapse-item>

                    <el-collapse-item title="审核信息" name="1">
                        <el-row>
                            <el-col :span="24">
                                <el-steps class="" direction="vertical" :active="1" :space="20">
                                    <div style="max-height: 350px;overflow-y: auto">
                                        <el-step v-for="(item,index) in refundDetailsData.auditRecordList" :key="index" :title="refundDetailsFn.parseAuthRemark(item.authRemark)">
                                            <template v-slot:description>
                                                <div style="margin-bottom: 20px" v-if="item.authRemark != refundDetailsData.hint">
                                                    <p>审核人：{{item.authName}}</p>
                                                    <p>审核时间：{{item.createdAt}}</p>
                                                    <p>{{(item.authRemark == 2 || item.authRemark == 4) ? ("驳回理由："+item.authReason) : ""}}</p>
                                                </div>
                                            </template>
                                        </el-step>
                                    </div>
                                </el-steps>
                            </el-col>
                        </el-row>

                    </el-collapse-item>

                </el-form>
            </el-collapse>
            <template #footer>
                              <span class="dialog-footer">
                                <el-button @click="refundDetailsFn.closeDialog">取消</el-button>
                              </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
    import {reactive, ref} from "vue";
    import {getRefundInfoList, audit, getByRefundInfoId, getOrderMoneyByNo} from "@/api/refundManage.js";
    import { useRouter } from "vue-router";
    import {ElMessage} from "element-plus";

    export default {
        name: "refundManage",
        components:{},
        setup() {
            const { $data: tableData, $fn: tableFn } = tableModule();
            const { $data: auditData, $fn: auditFn } = auditModule(tableFn);
            const { $data: refundDetailsData, $fn: refundDetailsFn } = refundDetailsModule();

            const auditForm = ref(null);
            const labelPosition = ref('right')

            return {
                tableData,
                tableFn,
                auditData,
                auditFn,
                auditForm,
                refundDetailsData,
                refundDetailsFn,
                labelPosition,
            };
        },
    };

    // 表格功能模块，包括搜索，分页等
    function tableModule() {
        const router = useRouter();

        const backup = {
            query: {
                refundStatus: "",
                orderNo: "",// 订单号
                applyName: "",// 申请人
                applyPhone: "",// 申请人手机号
                createdAtStart: "",//申请时间-起(订单创建时间)
                createdAtEnd: "",//申请时间-止
                pageSize: 10,
                page: 1,
            },
        };

        const $data = reactive({
            query: { ...backup.query },
            special:{
                createdAt:[],
            },
            list: [],
            total: 0,
            orderstatusList:[
                //状态（0-待业审，1-待财审，2-退款中，3-已退款，4-已驳回，5-退款失败）
                {
                    tabName: "待业审",
                    refundStatus: "0",
                    tableCode: "refundOrder0",
                },
                {
                    tabName: "待财审",
                    refundStatus: "1",
                    tableCode: "refundOrder1",
                },
                {
                    tabName: "退款中",
                    refundStatus: "2",
                    tableCode: "refundOrder2",
                },
                {
                    tabName: "已退款",
                    refundStatus: "3",
                    tableCode: "refundOrder3",
                },
                {
                    tabName: "已驳回",
                    refundStatus: "4",
                    tableCode: "refundOrder4",
                },
                {
                    tabName: "退款失败",
                    refundStatus: "5",
                    tableCode: "refundOrder5",
                },
            ],
        });
        const $fn = {
            // refundDetails toOrderDetails orderAudit
            handleClick({props}){
                $data.query.refundStatus = props.name;
                $fn.getTableList();
            },
            // 获取表数据
            getTableList() {
                if(!$data.query.refundStatus){
                    $data.query.refundStatus = "0";
                }
                getRefundInfoList($data.query).then((res) => {
                    if (res.code === 0) {
                        $data.list = res.data.items;
                        $data.total = res.data.pagination.total_record;
                    }
                });
            },
            // 重置
            onResetQuery() {
                let refundStatus = $data.query.refundStatus;
                $data.query = { ...backup.query };
                $data.query.refundStatus = refundStatus;
                $data.special.createdAt = [];
                $fn.getTableList();
            },
            // 搜索
            onSubmit() {
                $fn.getTableList();
            },
            detetimeChange(time){
                time = time||[];
                $data.special.createdAt = time;
                $data.query.createdAtStart = time[0]||"";
                $data.query.createdAtEnd = time[1]||"";
            },
            // 退款详情
            refundDetails(row){

            },
            // 订单详情
            toOrderDetails(row){
            // （0-活动订单）
                if(row.orderType == '0'){
                    router.push(`/orderCare/eventsOrder/seeOrderDetail/${row.orderId}`)
                }
            },
            // 审核
            orderAudit(row){

            },
        };

        $fn.getTableList();

        return {
            $data,
            $fn,
        };
    }

    // 审核
    function auditModule(tableFn) {
        const $data = reactive({
            obj:{},
            auditVisible: false,
            auditRules:{
                auditRules:[{ required: true, message: "请选择", trigger: 'blur' }],
                refundMoney:[{ required: true, message: "请输入金额", trigger: 'blur' }],
                rejectReason:[{ required: true, message: "请填写驳回理由", trigger: 'blur' }],
            },
        });
        const $fn = {
            auditSubmit(formEl){
                if (!formEl) return
                formEl.validate((valid) => {
                    if(valid){
                        // 退款金额校验，大于0，必须小于等于，申请退款金额
                        if($data.obj.refundMoney == 0){
                            return ElMessage.warning('退款金额不能为零');
                        }
                        if($data.obj.refundMoney * 100 > $data.obj.applyRefundMoney){
                            return ElMessage.warning('退款金额不可大于申请金额');
                        }
                        if($data.obj.auditRes == '1'){
                            $data.obj.rejectReason = '0'
                        }
                        let data = {
                            id: $data.obj.id,
                            refundStatus: $data.obj.refundStatus,
                            auditRes: $data.obj.auditRes,
                            rejectReason: $data.obj.rejectReason,
                            refundMoney: $data.obj.refundMoney*100
                        }
                        audit(data).then(res=>{
                            if(res.code == 0){
                                ElMessage.success("修改成功");
                                $fn.closeDialog();
                            }
                        })
                    } else {
                        return false
                    }
                })
            },
            payMoneyChangeHandle(value){
                $data.obj.refundMoney = commonFunction().$fn.disposeInputValue(value)
            },
            // obj：被修改对象
            openDialog(obj){
                if(!obj || !obj.id){
                    $data.auditVisible = false;
                    return ElMessage.warning('审核对象不存在，请刷新页面重试');
                }
                $data.obj = JSON.parse(JSON.stringify(obj));
                $data.obj.refundMoney = obj.refundMoney ? obj.refundMoney/100 : obj.applyRefundMoney/100;
                $data.obj.auditRes = "1";
                $data.auditVisible = true;
            },
            closeDialog(){
                $data.obj = {};
                $data.auditVisible = false;
                tableFn.getTableList();
            }
        };
        return {
            $data,
            $fn,
        };
    }

    // 退款详情
    function refundDetailsModule() {
        const $data = reactive({
            obj:{},
            refundDetailsVisible: false,
            orderTypeList:[
                {
                    key:"0",
                    value:"活动订单",
                },
                {
                    key:"1",
                    value:"洗护订单",
                },
                {
                    key:"2",
                    value:"托运订单",
                },
            ],
            auditRecordList:[],
            activeNames:['0','1'],
            authRemarkSource:[
                {
                    key:"1",
                    value:"业审通过",
                },
                {
                    key:"2",
                    value:"业审驳回",
                },
                {
                    key:"3",
                    value:"财审通过",
                },
                {
                    key:"4",
                    value:"财审驳回",
                },
            ],
            hint: "打款成功",
        });
        const $fn = {
            // obj：查看对象
            openDialog(obj){
                if(!obj || !obj.id){
                    $data.refundDetailsVisible = false;
                    return ElMessage.warning('对象不存在，请刷新页面重试');
                }
                $data.obj = obj;
              // 审核信息查询
              getOrderMoneyByNo(obj.orderId,obj.orderType).then(res=>{
                if(res.code ==0){
                  $data.obj.orderMoney = res.data.orderMoney
                  $data.obj.payMoney = res.data.payMoney
                  $data.obj.couponMoney = res.data.couponMoney
                }else{
                  $data.obj.orderMoney = 0
                  $data.obj.payMoney = 0
                  $data.obj.couponMoney = 0
                }
              })

                // 审核信息查询
                getByRefundInfoId(obj.id).then(res=>{
                    if(res.code ==0){
                        $data.auditRecordList = res.data;
                        if(obj.refundStatus && obj.refundStatus == 3){
                            $data.auditRecordList.push({
                                authRemark: $data.hint,
                            })
                        }
                    }else{
                        $data.auditRecordList = [];
                    }
                })
                $data.refundDetailsVisible = true;
            },
            parseOrderType(orderType){
                if(!orderType){
                    return '-';
                }
                let item = $data.orderTypeList.find(i=>{
                   return i.key == orderType
                })
                return !item?"-":item.value;
            },
            closeDialog(){
                $data.obj = {};
                $data.refundDetailsVisible = false;
            },
            parseAuthRemark(authRemark){
                if(!authRemark){
                    return '-';
                }
                if(authRemark == $data.hint){
                    return authRemark;
                }
                let item = $data.authRemarkSource.find(i => i.key == authRemark);
                return !!item?item.value:"-";
            },
        };
        return {
            $data,
            $fn,
        };
    }

    function commonFunction(){
        const $data = reactive({});

        const $fn = {
            disposeInputValue(num) {
                if(!num && num != '0'){
                    return "";
                }
                let str = num
                let len1 = str.substr(0, 1)
                let len2 = str.substr(1, 1)
                //如果第一位是0，第二位不是点，就用数字把点替换掉【去掉数字前面无用的0】
                if (str.length > 1 && len1 == 0 && len2 != '.') {
                    str = str.substr(1, 1)
                }
                //第一位不能是.
                if (len1 == '.') {
                    str = ''
                }
                //限制只能输入一个小数点
                if (str.indexOf('.') != -1) {
                    var str_ = str.substr(str.indexOf('.') + 1)
                    if (str_.indexOf('.') != -1) {
                        str = str.substr(0, str.indexOf('.') + str_.indexOf('.') + 1)
                    }
                }
                //正则替换
                str = str.replace(/[^\d^.]+/g, '') // 保留数字和小数点
                if(str.indexOf('.') == -1 || str.indexOf('.') == str.length-1){
                    return str
                }
                let strings = str.split(".");
                return strings[0] + "." + strings[1].substr(0,strings[1].length > 2 ? 2 : strings[1].length)

                // let tempNum = str * 100;
                // tempNum = parseInt(tempNum);
                // str = tempNum / 100;
                // return str
            },
            /***
             * 获取请求的UUID，指定长度和进制,如
             * getUUID(8, 2)   //"01001010" 8 character (base=2)
             * getUUID(8, 10) // "47473046" 8 character ID (base=10)
             * getUUID(8, 16) // "098F4D35"。 8 character ID (base=16)
             */
            getUUID(len, radix) {
                let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
                let uuid = [], i;
                radix = radix || chars.length;
                if (len) {
                    for (let i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
                } else {
                    let r;
                    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
                    uuid[14] = '4';
                    for (let i = 0; i < 36; i++) {
                        if (!uuid[i]) {
                            r = 0 | Math.random() * 16;
                            uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                        }
                    }
                }
                return uuid.join('');
            },
        };

        return {
            $data,
            $fn,
        };
    }
</script>

<style scoped lang="scss">
    @import "@/styles/tablePage.scss";

    :deep(.el-form-item__label){
        display: flex;
        align-items: center;
    }
    .orderInfoClass{
        font-size: 14px;
    }
    :deep(.el-tabs__nav-wrap::after){
        background-color: transparent !important;
    }
</style>

